#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <vector>

const int PORT = 8080;
const int BUFFER_SIZE = 1024;
uint8_t crc8(uint8_t *data, uint16_t length);
uint8_t crc8(uint8_t *data, uint16_t length)
{
    uint8_t i;
    uint8_t crc = 0;
    while(length--)
    {
        crc ^= *data++;
        for ( i = 0; i < 8; i++ )
        {
            if ( crc & 0x80 )
                crc = (crc << 1) ^ 0x07;
            else
                crc <<= 1;
        }
    }
    return crc;
}


int main() {
    int serverSocket, clientSocket;
    struct sockaddr_in serverAddr, clientAddr;
    socklen_t addrLen = sizeof(clientAddr);

    // 创建套接字
    if ((serverSocket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("Socket creation error");
        return 1;
    }

    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_port = htons(PORT);

    // 绑定地址和端口
    if (bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) {
        perror("Binding error");
        return 1;
    }

    // 监听连接
    if (listen(serverSocket, 5) < 0) {
        perror("Listening error");
        return 1;
    }

    std::cout << "Server listening on port " << PORT << std::endl;

    // 接受客户端连接
    if ((clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &addrLen)) < 0) {
        perror("Accepting error");
        return 1;
    }

    std::cout << "Client connected" << std::endl;

    std::ofstream outputFile("received_file.txt", std::ios::out | std::ios::binary);

    // 接收文件数据
    char buffer[BUFFER_SIZE];
    int bytesRead;
    std::string data;

    // 接收数据
    while (true) {
        bytesRead = recv(clientSocket, buffer, BUFFER_SIZE, 0);
        if (bytesRead < 0) {
            perror("Receiving error");
            break;
        } else if (bytesRead == 0) {
            // 客户端关闭连接
            std::cout << "Client disconnected" << std::endl;
            break;
        } else {
            data.append(buffer, bytesRead);
        }
    }

    std::cout << "Received data: " << data << std::endl;

    // 进行CRC8校验
    if (data.length() > 0) {
        uint8_t receivedCRC = static_cast<uint8_t>(data[data.length() - 1]);  // 获取最后一个字节作为CRC8校验值
        data.resize(data.size() - 1);  // 去掉最后一个字节，以便进行校验
        uint8_t calculatedCRC = crc8(const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(data.data())), data.length());  // 计算CRC8
        if (receivedCRC == calculatedCRC) {
            std::cout << "CRC8 check passed." << std::endl;

            // 保存数据到文件
            std::ofstream outputFile("received_data.txt", std::ios::binary);
            if (outputFile) {
                outputFile.write(data.data(), data.length());
                outputFile.close();
                std::cout << "Data saved to file: received_data.txt" << std::endl;
            } else {
                std::cerr << "Failed to open file for writing." << std::endl;
            }
        } else {
            std::cerr << "CRC8 check failed!" << std::endl;
        }
    }



      outputFile.close();

    // 关闭套接字
    close(clientSocket);
    close(serverSocket);

    //std::cout << "File received and saved as 'received_file.txt'" << std::endl;

    return 0;
}
